//实现时间组件的前后日期范围控制
Ext.apply(Ext.form.field.VTypes, {
    daterange: function(val, field){   // 调用 daterange 
        var date = field.parseDate(val);
        if(!date){
            return false;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))){
            var start = field.up('form').down('#' + field.startDateField);
            start.setMaxValue(date);
            this.dateRangeMax = date;
            start.validate();
        }else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))){
            var end = field.up('form').down('#' + field.endDateField);
            end.setMinValue(date);
            this.dateRangeMin = date;
            end.validate();
        }
        return true;
    }
});
//取得cookie    
function getCookie(name) {    
 var nameEQ = name + "=";    
 var ca = document.cookie.split(';');    //把cookie分割成组    
 for(var i=0;i < ca.length;i++) {    
 var c = ca[i];                      //取得字符串    
 while (c.charAt(0)==' ') {          //判断一下字符串有没有前导空格    
 c = c.substring(1,c.length);      //有的话，从第二位开始取    
 }    
 if (c.indexOf(nameEQ) == 0) {       //如果含有我们要的name    
 return unescape(c.substring(nameEQ.length,c.length));    //解码并截取我们要值    
 }    
 }    
 return false;    
}  

var _win = null;
function iframeshow(tle, url, w, h, r, max,iframeId,winId) {
	_win = new Ext.Window({
		title : tle,
		width : w,
		id:winId,
		height : h,
		isTopContainer : true,
		modal : true,
		resizable : r,
		draggable : false,
		maximizable : max,
		hidden : true,
		border:false,
		contentEl : Ext.DomHelper.append(document.body, {
			tag : 'iframe',
			src : url,
			height : '100%',
			border : false,
			id:iframeId,
			frameBorder : '0',
			width : '100%'
		}),
		animate : true
	});
	_win.show();
}

/**
 * 重载iframeshow这个方法
 * 
 * @param {Object} windowTitle
 * @param {Object} url
 * @param {Object} width
 * @param {Object} height
 */
function getContent(windowTitle,url,width,height){
	iframeshow(windowTitle,url,width,height,false,false);
}

function Request(strName) {
	var strHref = document.location.href;
	var intPos = strHref.indexOf('?');
	var strRight = strHref.substr(intPos + 1);
	var arrTmp = strRight.split('&');
	for (var i = 0; i < arrTmp.length; i++) {
		var arrTemp = arrTmp[i].split('=');
		if (arrTemp[0].toUpperCase() == strName.toUpperCase())
			return arrTemp[1];
	}
	return 0;
}

var FunToolKit = {};
FunToolKit.getRandom = function(n) {
	return Math.floor(Math.random() * n + 1)
}

function fnEnterClick(id, fid) {
	$('#' + fid).live('keyup', function(e) {
		e = e || event;
		var keycode = e.keyCode;
		var browserName = navigator.appName;
		if (keycode == 13) {
			if (browserName == 'Netscape') {// ff
				var evt = document.createEvent('MouseEvents');
				evt.initEvent('click', false, false);
				document.getElementById(id).dispatchEvent(evt);
				// return true;
			} else if (browserName == 'Microsoft Internet Explorer') {// ie
				document.getElementById(id).click();
			}
		}
	});
}

// -------------------MWJ----------------------
/**
 * 字符串的去头尾空白函数
 * 
 * @return {本字符串}
 */
String.prototype.trimSpace = function() {
	return this.replace(/(^\s*)|(\s*$)/g, '');
}

/**
 * 字符串的去所有空白函数
 * 
 * @return {本字符串}
 */
String.prototype.trimAllSpace = function() {
	return this.replace(/\s*/g, '');
}

Date.prototype.matchStr = function(str) {
	var tmp;
	if (str == 'MM') {
		tmp = this.getMonth() + 1;
		return tmp < 10 ? '0' + tmp + '-' : tmp + '-';
	} else if (str == 'dd') {
		tmp = this.getDate();
		return tmp < 10 ? '0' + tmp : tmp;
	} else if (str == 'yyyy') {
		return this.getFullYear() + '-';
	} else if (str == 'hh') {
		tmp = this.getHours();
		return tmp < 10 ? '0' + tmp + ':' : tmp + ':';
	} else if (str == 'mm') {
		tmp = this.getMinutes();
		return tmp < 10 ? '0' + tmp + ':' : tmp + ':';
	} else if (str == 'ss') {
		tmp = this.getSeconds();
		return tmp < 10 ? '0' + tmp + ':' : tmp + ':';
	} else {
		return '';
	}
}

/*var tempXhr = null;
$(document).ajaxComplete(function(event, xhr, ajaxOptions){
	tempXhr = xhr;
});*/
//清除cookie    
function clearCookie(name) {    
 setCookie(name, "", -1);    
}
//设置cookie    
function setCookie(name, value, seconds) {    
 seconds = seconds || 0;   //seconds有值就直接赋值，没有为0，这个根php不一样。    
 var expires = "";    
 if (seconds != 0 ) {      //设置cookie生存时间    
 var date = new Date();    
 date.setTime(date.getTime()+(seconds*1000));    
 expires = "; expires="+date.toGMTString();    
 }    
 document.cookie = name+"="+escape(value)+expires+"; path=/";   //转码并赋值    
} 
Ext.onReady(function() {
	window.onbeforeunload = function(){
		clearCookie("username");
		clearCookie("host");
	}
});
//对于session失效的处理
Ext.Ajax.on('requestcomplete',function(conn,response,options) {
	var projectPath = null;
	try{
		projectPath = response.getResponseHeader('projectPath');
	}catch(e){
		if(tempXhr!=null){
			projectPath = tempXhr.getResponseHeader('projectPath');
		}
	}
	if(projectPath){
		Ext.Msg.alert('提示', '会话超时，请重新登录!', function(){
			clearCookie("username");
			clearCookie("host");
			window.top.location = projectPath;
		});
	}
});

//重写分页组件pagingtoolbar的getPagingItems方法
Ext.override(Ext.toolbar.Paging, {
	submitText:'确定',
	pageText:'第{0}页,共{1}页',
	tipText:'跳转至',
	doSubmit:function(field, e){
	 	var me = this,
            pageData = me.getPageData(),
            pageNum;

        e.stopEvent();
        pageNum = me.readPageFromInput(pageData);
        if (pageNum !== false) {
            pageNum = Math.min(Math.max(1, pageNum), pageData.pageCount);
            if(me.fireEvent('beforechange', me, pageNum) !== false){
                me.store.loadPage(pageNum);
            }
        }
	},
    onPagingBlur : function(e){
        var inputItem = this.getInputItem(),
            curPage;
            
        if (inputItem) {
            curPage = this.getPageData().currentPage;
            //inputItem.setValue(curPage);
        }
    },
    onLoad : function(){
        var me = this,
            pageData,
            currPage,
            pageCount,
            pageText,
            count,
            isEmpty,
            item;

        count = me.store.getCount();
        isEmpty = count === 0;
        if (!isEmpty) {
            pageData = me.getPageData();
            currPage = pageData.currentPage;
            pageCount = pageData.pageCount;
            pageText = Ext.String.format(me.pageText, isNaN(pageCount) ? 1 : currPage, isNaN(pageCount) ? 1 : pageCount);
        } else {
            currPage = 0;
            pageCount = 0;
            pageText = Ext.String.format(me.pageText, 0, 0);
        }

        Ext.suspendLayouts();
        item = me.child('#pageTextItem');
        if (item) {    
            item.setText(pageText);
        }
        item = me.getInputItem();
        if (item) {
            item.setDisabled(isEmpty).setValue(currPage);
        }
        
        me.setChildDisabled('#first', currPage === 1 || isEmpty);
        me.setChildDisabled('#prev', currPage === 1 || isEmpty);
        me.setChildDisabled('#next', currPage === pageCount  || isEmpty);
        me.setChildDisabled('#last', currPage === pageCount  || isEmpty);
        me.setChildDisabled('#submit', false);
        me.setChildDisabled('#refresh', false);
        me.updateInfo();
        Ext.resumeLayouts(true);

        if (me.rendered) {
            me.fireEvent('change', me, pageData);
        }
    },
    beforeLoad : function(){
        if (this.rendered) {
            this.setChildDisabled('#refresh', true);
            this.setChildDisabled('#submit', true);
        }
    },
    onLoadError : function(){
        if (!this.rendered) {
            return;
        }
        this.setChildDisabled('#refresh', false);
        this.setChildDisabled('#submit', true);
    },
	getPagingItems: function() {
        var me = this;

        return [{
            itemId: 'first',
            tooltip: me.firstText,
            overflowText: me.firstText,
            iconCls: Ext.baseCSSPrefix + 'tbar-page-first',
            disabled: true,
            handler: me.moveFirst,
            scope: me
        },{
            itemId: 'prev',
            tooltip: me.prevText,
            overflowText: me.prevText,
            iconCls: Ext.baseCSSPrefix + 'tbar-page-prev',
            disabled: true,
            handler: me.movePrevious,
            scope: me
        },
        '-',
        {
            xtype: 'tbtext',
            itemId: 'pageTextItem',
            text: Ext.String.format(me.pageText, 1)
        },
        '-',
        {
            xtype: 'tbtext',
            itemId: 'tipTextItem',
            text: me.tipText
        },
        {
            xtype: 'numberfield',
            itemId: 'inputItem',
            name: 'inputItem',
            cls: Ext.baseCSSPrefix + 'tbar-page-number',
            allowDecimals: false,
            minValue: 1,
            hideTrigger: true,
            enableKeyEvents: true,
            keyNavEnabled: false,
            selectOnFocus: true,
            submitValue: false,
            
            isFormField: false,
            width: me.inputItemWidth,
            margins: '-1 2 3 2',
            listeners: {
                scope: me,
                keydown: me.onPagingKeyDown,
                blur: me.onPagingBlur
            }
        },{
            itemId: 'submit',
            text: me.submitText,
            tooltip: me.submitText,
            overflowText: me.submitText,
            handler: me.doSubmit,
            scope: me
        },
        '-',
        {
            itemId: 'next',
            tooltip: me.nextText,
            overflowText: me.nextText,
            iconCls: Ext.baseCSSPrefix + 'tbar-page-next',
            disabled: true,
            handler: me.moveNext,
            scope: me
        },{
            itemId: 'last',
            tooltip: me.lastText,
            overflowText: me.lastText,
            iconCls: Ext.baseCSSPrefix + 'tbar-page-last',
            disabled: true,
            handler: me.moveLast,
            scope: me
        },
        '-',
        {
            itemId: 'refresh',
            tooltip: me.refreshText,
            overflowText: me.refreshText,
            iconCls: Ext.baseCSSPrefix + 'tbar-loading',
            handler: me.doRefresh,
            scope: me
        }];
    }
});